package models

import (
	"github.com/jinzhu/gorm"
)

type RentRecord struct {
	Model

	UserId int  `json:"user_id" gorm:"index"`
	User   User `json:"user"`

	Room      string `json:"room" gorm:"index"`
	StartTime int64  `json:"start_time"`
	EndTime   int64  `json:"end_time"`

	RentKey string `json:"rent_key"`
}

func ExistRentById(id int) (bool, error) {
	var rent RentRecord
	err := db.Select("id").Where("id = ? AND deleted_on = ?", id, 0).First(&rent).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return rent.ID > 0, err
}

func ExistRentByUser(userId int) (bool, error) {
	var rent RentRecord
	err := db.Select("id").Where("user_id = ? AND deleted_on = ?", userId, 0).First(&rent).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return rent.ID > 0, nil
}
func ExistRentByRoom(room string, startTime, endTime int64) (bool, error) {
	var rent RentRecord
	err := db.Select("id").Where("Room = ? AND deleted_on = ? AND " +
		"((start_time <= ? AND start_time >= ?) OR (end_time <= ? AND end_time >= ?))",
		room, 0, endTime, startTime, endTime, startTime).
		First(&rent).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return rent.ID > 0, nil
}

func AddRent(data map[string]interface{}) error {
	rent := RentRecord{
		UserId:    data["user_id"].(int),
		Room:      data["room"].(string),
		StartTime: data["start_time"].(int64),
		EndTime:   data["end_time"].(int64),
		RentKey:   data["rent_key"].(string),
	}
	err := db.Create(&rent).Error

	return err
}

func GetRentByUser(userId int) (RentRecord, error) {
	var rent RentRecord
	err := db.Where("user_id = ? AND deleted_on = ?", userId, 0).First(&rent).Error
	if err != nil {
		return rent, err
	}
	return rent, nil
}

func GetRentTotal(maps interface{}) (int, error) {
	var count int
	err := db.Model(&RentRecord{}).Where(maps).Count(&count).Error
	if err != nil {
		count = 0
	}
	return count, err
}

func GetRents(pageNum int, pageSize int, maps map[string]interface{}) ([]*RentRecord, error) {
	var rents []*RentRecord
	r := db.Preload("User").Where(maps)
	if maps["start_range"] != nil {
		start := maps["start_range"].([]int64)
		r = r.Where("start_time between ? and ?", start[0], start[1])
	}
	if maps["end_range"] != nil {
		end := maps["end_range"].([]int64)
		r = r.Where("end_time between ? and ?", end[0], end[1])
	}
	err := r.Where(maps).Offset(pageNum).Limit(pageSize).Find(&rents).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return rents, nil
}

func DeleteRent(id int) error {
	err := db.Where("id = ?", id).Delete(&RentRecord{}).Error
	return err
}

func CleanAllRent() error {
	err := db.Unscoped().Where("deleted_on != ?", 0).Delete(&RentRecord{}).Error
	return err
}
